package com.xl.qa.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xl.basic.entity.Result;
import com.xl.basic.entity.ResultEnums;
import com.xl.basic.entity.UserInfo;
import com.xl.basic.utils.JacksonUtils;
import com.xl.dao.domain.XlQuestionAnswer;
import com.xl.dao.domain.XlQuestionForm;
import com.xl.dao.mapper.XlQuestionAnswerMapper;
import com.xl.qa.entity.param.AddOrUpdQuesAnswerParam;
import com.xl.qa.entity.result.AddOrUpdQuesAnswerResult;
import com.xl.qa.service.QuestionAnswerService;
import com.xl.qa.service.QuestionFormService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 钟勇
 * Create in 2024/1/16 15:03
 */
@Service
@RequiredArgsConstructor
public class QuestionAnswerServiceImpl implements QuestionAnswerService {

    private final XlQuestionAnswerMapper answerMapper;
    private final QuestionFormService formService;

    @Override
    public Result<List<XlQuestionAnswer>> queryQuesAnswer(@NonNull String orderId) {
        List<XlQuestionAnswer> list = answerMapper.selectList(new LambdaQueryWrapper<XlQuestionAnswer>()
                .eq(XlQuestionAnswer::getState, 1)
                .eq(XlQuestionAnswer::getOrderId, orderId)
                .orderByAsc(XlQuestionAnswer::getRowSortIndex)
        );
        return ResultEnums.Success.getListResult(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 300)
    public Result<List<AddOrUpdQuesAnswerResult>> addOrUpdQuesAnswer(@NonNull AddOrUpdQuesAnswerParam param, UserInfo operator) {
        String operatorUserId = operator != null ? operator.getUserId() : null;
        ObjectMapper objectMapper = JacksonUtils.objectMapper();

        //回答内容
        List<AddOrUpdQuesAnswerParam.AnswerRow> answerRowList = new ArrayList<>();
        if (StrUtil.isNotBlank(param.getAnswerJsonStr())) {
            try {
                answerRowList = objectMapper.readValue(param.getAnswerJsonStr(), new TypeReference<>() {
                });
            } catch (JsonProcessingException e) {
                return ResultEnums.Exception.getResult(e.toString());
            }
        }

        Result<List<XlQuestionForm>> quesRes = formService.queryQuestionForm(param.getQuestionId());
        if (quesRes.isErr()) {
            return quesRes.create();
        }

        List<XlQuestionForm> rowList = quesRes.getResult();
        if (rowList == null || rowList.isEmpty()) {
            return ResultEnums.BusinessError.getResult("未找到对应的问卷内容");
        }

        //写入系统回答的集合
        List<XlQuestionAnswer> list = new ArrayList<>();
        List<AddOrUpdQuesAnswerResult> cutList = new ArrayList<>();

        for (XlQuestionForm row : rowList) {
            Integer rowId = row.getRowId();
            AddOrUpdQuesAnswerParam.AnswerRow answerRow = answerRowList.stream()
                    .filter(item -> item.getRowId().equals(rowId))
                    .findFirst().orElse(null);


            if (answerRow == null || StrUtil.isBlank(answerRow.getRowValue())) {
                if (row.getRowMustFlag() != null && row.getRowMustFlag().equals(1)) {
                    return ResultEnums.ParamError.getResult(row.getRowTitle() + "不能为空");
                }
            } else {
                list.add(new XlQuestionAnswer()
                        .setOrderId(param.getOrderId())
                        .setQuestionId(param.getQuestionId())
                        .setRowId(rowId)
                        .setRowTitle(row.getRowTitle())
                        .setRowValue(answerRow.getRowValue())
                        .setRowType(row.getRowType())
                        .setRowSortIndex(row.getSortIndex())
                        .setRowMustFlag(row.getRowMustFlag())
                        .setState(1)
                        .setAddTime(LocalDateTime.now())
                        .setAddUser(operatorUserId)
                );

                cutList.add(new AddOrUpdQuesAnswerResult()
                        .setTitle(row.getRowTitle())
                        .setValue(answerRow.getRowValue())
                        .setRowType(row.getRowType())
                        .setRowMustFlag(row.getRowMustFlag())
                );
            }
        }

        //删除所有旧的回答
        answerMapper.update(new XlQuestionAnswer()
                        .setState(0)
                        .setUpdTime(LocalDateTime.now())
                        .setUpdUser(operatorUserId)
                , new LambdaQueryWrapper<XlQuestionAnswer>()
                        .eq(XlQuestionAnswer::getOrderId, param.getOrderId())
        );


        for (XlQuestionAnswer data : list) {
            if (answerMapper.insert(data) == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultEnums.Exception.getResult("数据写入失败");
            }
        }

        return ResultEnums.Success.getListResult(cutList);
    }
}
